<template>
  <view class="container" :style="appThemeStyle">
    <u-dropdown ref="uDropdown">
      <u-dropdown-item v-model="queryParams.replyStatus" :value="queryParams.replyStatus" :title="replyTitle" :options="replyOptions" @change="changeReply"></u-dropdown-item>
      <u-dropdown-item v-model="queryParams.serviceScore" :value="queryParams.serviceScore" title="满意度" :options="serviceScoreOptions" @change="changeServiceScore"></u-dropdown-item>
      <u-dropdown-item v-model="queryParams.thirdChannelId" :value="queryParams.thirdChannelId" title="渠道" :options="channelOptions" @change="changeChannel"></u-dropdown-item>
      <u-dropdown-item title="评价时间">
        <view class="slot-content">
          <view class="title">筛选时间</view>
          <view class="date-wrap" @click="onCalendar">
            <view class="date-item">
              <view :class="{ active: startTime }">{{ startTime || '开始日期' }}</view>
              <text class="iconfont calendar">&#xe6c6;</text>
            </view>
            <view class="date-item">
              <view :class="{ active: startTime }">{{ endTime || '结束日期' }}</view>
              <text class="iconfont calendar">&#xe6c6;</text>
            </view>
          </view>
          <view class="btn-wrapper">
            <view class="btn-item" @click="handleReset">重置</view>
            <view class="btn-item active" @click="handleSearch">筛选</view>
          </view>
        </view>
      </u-dropdown-item>
    </u-dropdown>
    <mescroll-body
      ref="mescrollRef"
      :sticky="true"
      @init="mescrollInit"
      :down="{ native: true }"
      :up="upOption"
      @up="upCallback"
      @down="downCallback"
    >
      <view class="comment-list">
        <view class="comment-item" v-for="(item, index) in commentList" :key="index">
          <view class="header">
            <view class="icon" :style="{ backgroundColor: getChannelCls(item.thirdChannelId) }">{{ getChannelName(item.thirdChannelId) }}</view>
            <view class="text">
              <view class="name">{{ item.shopName }}</view>
              <view class="time">{{ item.commentTime }}</view>
            </view>
          </view>
          <view class="rate-wrap">
            <view class="rate-item">
              <text class="label">满意程度</text>
              <text class="score">{{ item.serviceScore }}.0</text>
              <text class="iconfont">{{ item.serviceScore === 5 ? '&#xe6a3;' : '&#xe6b5;' }}</text>
            </view>
            <view class="rate-item">
              <text class="label">质量评分</text>
              <text class="score">{{ item.qualityScore }}.0</text>
              <text class="iconfont">{{ item.qualityScore === 5 ? '&#xe6a3;' : '&#xe6b5;' }}</text>
            </view>
            <view class="rate-item">
              <text class="label">包装评分</text>
              <text class="score">{{ item.packingScore }}.0</text>
              <text class="iconfont">{{ item.packingScore === 5 ? '&#xe6a3;' : '&#xe6b5;' }}</text>
            </view>
          </view>
          <view class="comment-text">{{ item.commentContent }}</view>
          <view class="comment-pic" v-if="item.commentPicUrl">
            <image v-for="(pItem, pIndex) in item.commentPicUrl.split(',')" :key="pIndex" :src="pItem" mode="aspectFill"></image>
          </view>
          <view class="goods-list">
            <view class="goods-item" v-for="(gItem, gIndex) in orderGoodsComments(item)" :key="gIndex">
              <view class="title">{{ gItem.goodsName }}</view>
              <u-rate
                :count="1"
                v-model="isPraise"
                :disabled="true"
                :active-color="gItem.isPraise === 2 ? '#C9CDD4' : '#ffc454'"
                :active-icon="gItem.isPraise === 2 ? 'thumb-down-fill' : 'thumb-up-fill'"
              />
            </view>
            <view
              v-if="item.orderGoodsComments?.length > 2"
              :class="['iconfont icon-arrow-down', { 'icon-arrow-up': item.showMore }]"
              @click="handleMore(item)"
            ></view>
          </view>
          <view class="btn-wrapper">
            <u-button
              type="primary"
              :custom-style="{
                height: '60rpx'
              }"
              @click.stop="reply(item)"
            >回复</u-button>
          </view>
        </view>
      </view>
    </mescroll-body>
    <u-modal
      v-model="showModal"
      title="回复评价"
      show-cancel-button
      :title-style="{
        fontWeight: 'bold'
      }"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <view class="modal-content">
        <u-input
          v-model="replyContent"
          type="textarea"
          :border="true"
          :height="100"
          :auto-height="true"
          :maxlength="50"
          placeholder="请输入评价描述"
        />
      </view>
    </u-modal>
    <!-- 日历组件 -->
    <u-calendar
      max-date="2050-01-01"
      v-model="showTime"
      mode="range"
      @change="changeDate"
    ></u-calendar>
  </view>
</template>
<script>

import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
import * as CommentApi from '@/api/order/comment'
import store from '@/store'

export default {
  name: "index",
  mixins: [MescrollMixin],
  data() {
    return {
      // 上拉加载配置
      upOption: {
        // 首次自动执行
        auto: true,
        // 每页数据的数量; 默认10
        page: { size: 10 },
        // 数量要大于3条才显示无更多数据
        noMoreSize: 3,
        empty: {
          tip: '这里空空如也~'
        }
      },
      showModal: false,
      replyContent: '',
      showTime: false,
      startTime: '',
      endTime: '',
      commentList: getEmptyPaginateObj(),
      queryParams: {
        thirdChannelId: '',
        replyStatus: '',
        serviceScore: ''
      },
      replyTitle: '全部',
      replyOptions: [
        { label: '全部', value: '' },
        { label: '有回复', value: 1 },
        { label: '无回复', value: 2 }
      ],
      serviceScoreTitle: '满意度',
      serviceScoreOptions: [
        { label: '全部', value: '' },
        { label: '好评（4-5星）', value: 3 },
        { label: '中评（3星）', value: 2 },
        { label: '差评（1-2星）', value: 1 }
      ],
      channelTitle: '渠道',
      isPraise: 1,
      currentRow: {}
    }
  },
  computed: {
    businessType() {
      return store.getters.businessType
    },
    channelList() {
      return store.getters.allChannels
    },
    getChannelCls() {
      return (val) => {
        return this.channelList.find(item => item.channelId === val)?.color
      }
    },
    getChannelName() {
      return (val) => {
        return this.channelList.find(item => item.channelId === val)?.abbreviation
      }
    },
    store() {
      return store.getters.store
    },
    channelOptions() {
      const list = this.channelList.map(item => ({ value: item.channelId, label: item.channelName }))
      return [ {label: '全部渠道', value: '' }, ...list ]
    },
    orderGoodsComments() {
      return (item) => {
        if (item.showMore) {
          return item.orderGoodsComments
        } else {
          return item.orderGoodsComments.slice(0, 2)
        }
      }
    }
  },
  onLoad() {
  },
  methods: {
    // 刷新列表
    onRefreshList() {
      this.commentList = getEmptyPaginateObj()
      setTimeout(() => this.mescroll.resetUpScroll(), 120)
    },
    /**
     * 上拉加载的回调 (页面初始化时也会执行一次)
     * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
     * @param {Object} page
     */
    upCallback(page) {
      this.getCommentList(page.num)
        .then(res => {
          const curPageLen = res.length
          this.mescroll.endBySize(curPageLen)
        })
        .catch(() => this.mescroll.endErr())
    },

    /**
     * 获取订单评价列表
     * @param {Number} current 页码
     */
    getCommentList(current = 1) {
      if (this.businessType !== 0) {
        this.queryParams.organizationIds = this.store.id
      } else {
        delete this.queryParams.organizationIds
      }
      return new Promise((resolve, reject) => {
        CommentApi.list({ ...this.queryParams,  current }, { load: false })
          .then(result => {
            const newList = result.data
            this.commentList = getMoreListData(newList, this.commentList, current)
            resolve(newList)
          })
          .catch(reject)
      })
    },
    handleMore(item) {
      item.showMore = !item.showMore
    },
    reply(item) {
      this.currentRow = item
      this.replyContent = ''
      this.showModal = true
    },
    changeReply(e) {
      this.replyTitle = this.replyOptions.find(item => item.value === e).label
      this.onRefreshList()
    },
    changeServiceScore(e) {
      this.serviceScoreTitle = this.serviceScoreOptions.find(item => item.value === e).label
      this.onRefreshList()
    },
    changeChannel(e) {
      this.channelTitle = this.channelOptions.find(item => item.value === e).label
      this.onRefreshList()
    },
    handleConfirm() {
      if (!this.replyContent) return this.$toast('请输入评价描述！')
      const { id, commentId, thirdChannelId, shopId } = this.currentRow
      CommentApi.reply({
        id,
        commentId,
        thirdChannelId,
        shopId,
        replyContent: this.replyContent
      }).then(res => {
        if (res.data) {
          this.$toast('操作成功')
          this.onRefreshList()
        }
      })
      this.showModal = false
    },
    handleCancel() {
      this.showModal = false
    },
    handleReset() {
      this.startTime = ''
      this.endTime = ''
      delete this.queryParams.startTime
      delete this.queryParams.endTime
      this.onRefreshList()
      this.closeDropdown()
    },
    handleSearch() {
      if (this.startTime && this.endTime) {
        this.queryParams.startTime = this.startTime + ' 00:00:00'
        this.queryParams.endTime = this.endTime + ' 23:59:59'
      }
      this.onRefreshList()
      this.closeDropdown()
    },
    closeDropdown() {
      this.$refs.uDropdown.close()
    },
    onCalendar() {
      this.showTime = true
    },
    changeDate(e) {
      this.startTime = this.$moment(e.startDate).format("YYYY-MM-DD")
      this.endTime = this.$moment(e.endDate).format("YYYY-MM-DD")
      this.showTime = false
    },
  }
}
</script>

<style scoped lang="scss">
.container {

  .comment-list {
    padding: 0 24rpx;

    .comment-item {
      padding: 24rpx;
      background: #fff;
      border-radius: 16rpx;
      margin-bottom: 16rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .header {
        display: flex;
        align-items: center;

        .icon {
          background: $main-bg;
          color: #fff;
          font-size: 24rpx;
          width: 64rpx;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 50%;
          text-align: center;
          margin-right: 10rpx;
        }

        .text {
          display: flex;
          flex-direction: column;
          justify-content: center;
          flex: 1;
          overflow: hidden;
          font-size: 26rpx;
          line-height: 40rpx;

          .name {
            font-weight: bold;
            color: #333;
          }

          .time {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }

      .rate-wrap {
        margin: 24rpx 0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .rate-item {
          display: flex;
          align-items: center;
          line-height: 50rpx;

          .label {
            color: #999999;
            font-size: 24rpx;
            margin-right: 15rpx;
          }

          .score {
            font-size: 24rpx;
            font-weight: 500;
            color: #333333;
            margin-right: 5rpx;
          }

          .iconfont {
            font-size: 32rpx;
            color: #ffc454;
          }
        }
      }

      .comment-text {
        font-size: 26rpx;
        color: #333;
        line-height: 40rpx;
        margin-bottom: 20rpx;
      }

      .comment-pic {

        image {
          width: 144rpx;
          height: 144rpx;
          border-radius: 4rpx;
          margin-right: 16rpx;
          margin-bottom: 16rpx;
        }
      }

      .goods-list {
        margin: 8rpx 0 24rpx;

        .goods-item {
          background: #F3F5FA;
          color: #333;
          font-size: 24rpx;
          padding: 20rpx 24rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 16rpx;
          border-radius: 16rpx;
        }

        .iconfont {
          font-size: 30rpx;
          display: flex;
          justify-content: center;
          color: #999999;
        }
      }

      .btn-wrapper {
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
    }
  }

  .modal-content {
    padding: 24rpx;
    box-sizing: border-box;
    text-align: center;
    font-size: 30rpx;
    color: #333333;
  }

  .slot-content {
    background: #ffffff;
    padding: 24rpx 32rpx;

    .title {
      font-size: 28rpx;
      color: #666;
    }

    .date-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 24rpx 0;

      .date-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 330rpx;
        padding: 10rpx;
        background: #F8F8F8;
        font-size: 24rpx;
        color: #cccccc;
        border-radius: 16rpx;

        .active {
          color: #333;
        }

        .calendar {
          color: #999;
          font-size: 30rpx;
        }
      }
    }

    .btn-wrapper {
      display: flex;
      justify-content: space-between;

      .btn-item {
        width: 300rpx;
        height: 96rpx;
        line-height: 96rpx;
        text-align: center;
        background: #fff;
        font-size: 34rpx;
        border-radius: 16rpx;
        border: 2rpx solid var(--eeeeee, #EEE);

        &.active {
          background: $main-bg;
          color: #fff;
        }
      }
    }
  }
}
</style>
